package com.org.zp.ctrl.company;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.org.base.ctrl.ActivityTaskManager;
import com.org.base.ctrl.BaseActivity;
import com.org.base.util.HttpUtils;
import com.org.base.util.HttpUtils.CallBack;
import com.org.base.util.URLHelper;
import com.org.base.widget.LoadMoreListView;
import com.org.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.org.base.widget.LoadMoreListViewWithProgress;
import com.org.zp.R;
import com.org.zp.app.RecApp;
import com.org.zp.ctrl.search.PositionActivity;
import com.org.zp.entity.company.CompanyPosition;

public class CompanyPostActivity extends BaseActivity {
	private RecApp mApp;

	private TextView headerTitle;
	private Button backbutton, top_right_btn;

	private List<CompanyPosition> positions = new ArrayList<CompanyPosition>();
	private CompanyPosition status_position = new CompanyPosition();
	private int select_position = -1;

	private LoadMoreListViewWithProgress viewWhitProgress;
	private LoadMoreListView listView;
	private LinearLayout linear;
	private ComPositionAdapter adapter;

	private int currentPage;
	private int totalPage;
	private int perPageCount = 14;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				loadDataTask();
				break;
			case 1:
				adapter.notifyDataSetChanged();
				break;
			case 2:

				Toast toast2 = Toast.makeText(CompanyPostActivity.this, "无反应",
						Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
				break;

			}
			super.handleMessage(msg);
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.position_search_result);
		mApp = (RecApp) this.getApplication();

		if (!(ActivityTaskManager.getInstance()
				.containsName("CompanyPostActivity"))) {
			ActivityTaskManager.getInstance().putActivity(
					"CompanyPostActivity", this);
		}

		// 返回按钮
		backbutton = (Button) findViewById(R.id.back);
		backbutton.setText("  返回");
		backbutton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ActivityTaskManager.getInstance().removeActivity(
						"CompanyPostActivity");
			}
		});
		// 标题
		headerTitle = (TextView) findViewById(R.id.headTitle);
		headerTitle.setText("公司职位列表 ");

		top_right_btn = (Button) findViewById(R.id.top_right_button);
		top_right_btn.setVisibility(View.GONE);

		init();

	}

	private void init() {

		linear = (LinearLayout) findViewById(R.id.search_job_result_linear);

		adapter = new ComPositionAdapter(positions);

		viewWhitProgress = new LoadMoreListViewWithProgress(this);
		listView = viewWhitProgress.getListView();

		listView.setAdapter(adapter);
		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				loadDataTask();
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (((RecApp) getApplicationContext()).isNetWorkConnection) {

					Intent intent = new Intent(CompanyPostActivity.this,
							PositionActivity.class);
					intent.putExtra("Job_number", positions.get(position).getCom_position_id());
					startActivity(intent);

				} else {
					Toast toast2 = Toast.makeText(CompanyPostActivity.this,
							"网络连接断开，请检查网络", Toast.LENGTH_SHORT);
					toast2.setGravity(Gravity.CENTER, 0, 0);
					toast2.show();
				}

			}
		});

		linear.addView(viewWhitProgress);

		Message msg0 = new Message();
		msg0.what = 0;
		handler.sendMessage(msg0);

	}

	private void loadDataTask() {

		currentPage = currentPage + 1;
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "companyJobsList");
		map.put("uid", mApp.user.getuID());
		map.put("currentPage", String.valueOf(currentPage));
		map.put("rowCountPerPage", perPageCount + "");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				Log.e("TMG", "result = " + response.toString());
				try {
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {

						String currentPage = response.getString("currentPage");
						String totalPage = response.getString("totalPage");

						if (currentPage.equals(totalPage)) {
							listView.loadComplete(false);
						}

						String data = response.getString("dataList");
						JSONArray list = new JSONArray(data);

						for (int i = 0; i < list.length(); i++) {
							CompanyPosition info = new CompanyPosition();
							JSONObject log = list.getJSONObject(i);
							info.setCom_position_id(log.getString("id"));
							info.setCom_jobs_name(log.getString("jobs_name"));
							info.setCom_refreshtime(log.getString("refreshtime"));
							info.setCom_countresume(log.getString("countresume"));
							info.setCom_audit(log.getString("audit"));
							info.setCom_display(log.getString("display"));

							positions.add(info);
						}

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// We need notify the adapter that the data have been changed
				adapter.notifyDataSetChanged();
				viewWhitProgress.show();

			}

			@Override
			public void onFailure(Throwable e) {
				// TODO Auto-generated method stub

			}
		});

	}

	class ComPositionAdapter extends BaseAdapter {
		List<CompanyPosition> newsItems;

		public ComPositionAdapter(List<CompanyPosition> newsitems) {
			this.newsItems = newsitems;
		}

		@Override
		public int getCount() {
			return newsItems.size();
		}

		@Override
		public Object getItem(int position) {
			return newsItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			ViewHolder holder = null;
			if (null == view) {
				view = getLayoutInflater().inflate(
						R.layout.company_post_position_items, null);
				view.setBackgroundResource(R.drawable.list_bg_b);
				holder = new ViewHolder();
				holder.jobs_name = (TextView) view
						.findViewById(R.id.com_post_position_name);
				holder.refreshtime = (TextView) view
						.findViewById(R.id.com_post_position_reftime);
				holder.countresume = (TextView) view
						.findViewById(R.id.com_post_position_countresume);
				holder.audit = (TextView) view
						.findViewById(R.id.com_post_position_audit);
				holder.display = (Button) view
						.findViewById(R.id.com_post_position_display);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}
			holder.jobs_name
					.setText(newsItems.get(position).getCom_jobs_name());
			holder.refreshtime.setText("刷新时间：" + newsItems.get(position).getCom_refreshtime());
			holder.countresume.setText("已有" + newsItems.get(position).getCom_countresume() + "投递");
			holder.audit.setText(newsItems.get(position).getCom_audit());
			if("1".equals(newsItems.get(position).getCom_display())){
				holder.display.setText("暂停");
				holder.display.setOnClickListener(new startPositionListener(position));
			}else{
				holder.display.setText("开始");
			}
			
			return view;
		}

		class ViewHolder {
			TextView jobs_name;// 职位名称
			TextView refreshtime;// 刷新时间
			TextView countresume;// 简历投递次数
			TextView audit;// 审核状态
			Button display;// 开始暂停状态

		}

		/**
		 * 添加数据列表项
		 * 
		 * @param newsitem
		 */
		public void addNewsItem(CompanyPosition newsitem) {
			newsItems.add(newsitem);
		}
		
		class startPositionListener implements OnClickListener {

			startPositionListener(int pos) {
				select_position = pos;
			}

			@Override
			public void onClick(View v) {
				status_position = positions.get(select_position);
				new setJobStatusInfo().execute(URLHelper.mPrefix);
			}
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ActivityTaskManager.getInstance().removeActivity(
					"CompanyPostActivity");
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	class setJobStatusInfo extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>(); // 登录时向服务器发送的参数
			map.put("act", "activateJobs");
			map.put("uid", mApp.user.getuID());
			map.put("display", status_position.getCom_display());
			map.put("jobs_ids", status_position.getCom_position_id());

			return HttpUtils.readHttp(params[0], map);// 网络操作，向服务器发送登录请求，获取返回信息

		}

		@Override
		protected void onPostExecute(String result) {

			if (result == null || result.equals("")) {
				// 发送解析数据 消息
				Toast toast = Toast.makeText(CompanyPostActivity.this, "失败",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			} else if (result.equals("timeout")) {
				// 发送解析数据 消息
				Toast toast = Toast.makeText(CompanyPostActivity.this,
						"网络超时", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			} else {
				try {
					String succeed = new JSONObject(result)
							.getString("succeed");
					if (succeed.equals("000")) {
						Toast toast = Toast.makeText(
								CompanyPostActivity.this, "修改成功",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						
						if("1".equals(positions.get(select_position).getCom_display())){
							positions.get(select_position).setCom_display("2");
						}else{
							positions.get(select_position).setCom_display("1");
						}
						
						adapter.notifyDataSetChanged();
						
					}else{
						Toast toast = Toast.makeText(
								CompanyPostActivity.this, "修改失败",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		}
	}
}
